<template>
  <div class="user-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户列表</span>
          <el-button type="primary" @click="handleAdd">新增用户</el-button>
        </div>
      </template>
      <el-table :data="userData" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="realname" label="真实姓名" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="address" label="地址" />
        <el-table-column prop="gmtCreate" label="创建时间" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realname">
          <el-input v-model="userForm.realname" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!userForm.id">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="userForm.address" placeholder="请输入地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const submitLoading = ref(false)
const userData = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const userFormRef = ref(null)

// 表单数据
const userForm = reactive({
  id: '',
  username: '',
  realname: '',
  password: '',
  email: '',
  phone: '',
  address: ''
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  realname: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入地址', trigger: 'blur' }
  ]
}

// 获取用户列表
const getUserList = () => {
  loading.value = true
  axios({
    url: '/api/sysuser/sysUser/showAll',
    method: 'get'
  }).then((res) => {
    if (res.data.code === 200) {
      userData.value = res.data.data
    } else {
      ElMessage.error(res.data.msg || '获取用户列表失败')
    }
  }).catch((error) => {
    ElMessage.error('获取用户列表失败')
    console.error(error)
  }).finally(() => {
    loading.value = false
  })
}


// 重置表单
const resetForm = () => {
  if (userFormRef.value) {
    userFormRef.value.resetFields()
  }
  Object.assign(userForm, {
    id: '',
    username: '',
    realname: '',
    password: '',
    email: '',
    phone: '',
    address: ''
  })
}

// 新增用户
const handleAdd = () => {
  dialogTitle.value = '新增用户'
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row) => {
  dialogTitle.value = '编辑用户'
  Object.assign(userForm, {
    ...row,
    password: '' // 编辑时不显示密码
  })
  dialogVisible.value = true
}

// 删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除用户"${row.username}"吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    axios({
      url: `/api/sysuser/sysUser/deleteById/${row.id}`,
      method: 'delete'
    }).then((res) => {
      if (res.data.code === 200) {
        ElMessage.success('删除成功')
        getUserList()
      } else {
        ElMessage.error(res.data.msg || '删除失败')
      }
    }).catch((error) => {
      ElMessage.error('删除失败')
      console.error(error)
    })
  }).catch(() => {})
}

// 提交表单
const submitForm = () => {
  if (!userFormRef.value) return
  
  userFormRef.value.validate((valid) => {
    if (valid) {
      submitLoading.value = true
      const isEdit = !!userForm.id
      const url = isEdit 
        ? `/api/sysuser/sysUser/update/${userForm.id}`
        : '/api/sysuser/sysUser/add'
      const method = isEdit ? 'put' : 'post'

      // 如果是编辑且没有修改密码，则不提交密码字段
      const submitData = { ...userForm }
      if (isEdit && !submitData.password) {
        delete submitData.password
      }

      axios({
        url,
        method,
        data: submitData
      }).then((res) => {
        if (res.data.code === 200) {
          ElMessage.success(isEdit ? '修改成功' : '添加成功')
          dialogVisible.value = false
          getUserList()
        } else {
          ElMessage.error(res.data.msg || (isEdit ? '修改失败' : '添加失败'))
        }
      }).catch((error) => {
        ElMessage.error(isEdit ? '修改失败' : '添加失败')
        console.error(error)
      }).finally(() => {
        submitLoading.value = false
      })
    }
  })
}

onMounted(() => {
  getUserList()
})
</script>

<style lang="scss" scoped>
.user-container {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 